//
//  MadTodoListController.m
//  MadGTD
//
//  Created by Fuzhou Chen on 4/21/12.
//  Copyright (c) 2012 dummydigit.net. All rights reserved.
//

#import "MadTodoListController.h"
#include "MadDebug.h"
#include <sys/time.h>
#include <assert.h>

@interface MadTodoListController ()

@end

@implementation MadTodoListController

- (void)dealloc
{
    [super dealloc];
    if (_objects)
        [_objects release];
    if (_todoDetailsController)
        [_todoDetailsController release];
    if (_model)
        [_model release];
}

-(id)initWithGTDModel:(MadGTDModel*)model detailsViewController:(MadTodoDetailsViewController*)controller
{
    MAD_CHK_PARAM_OR_TERMINATE(model != nil, ("model == nil"));
    MAD_CHK_PARAM_OR_TERMINATE(controller != nil, ("detailsViewController == nil"));
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        _todoDetailsController = [controller retain];
        _objects = [[NSMutableArray alloc] init];
        _model = [model retain];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // TODO: Will make it async later
    [_model syncLoadDb];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)onAddNewTaskButtonClicked:(id)sender
{
}

- (void)insertNewObject:(id)sender
{
    if (!_objects) {
        _objects = [[NSMutableArray alloc] init];
    }
    /*
    struct timeval today;
    struct timezone tz;
    MadTodo newTodo;
    MadResult result = MAD_SUCCESS;
     */
    
    // Immediately ask for more information
    [_todoDetailsController viewWillAppear:YES];
    [self.navigationController pushViewController:_todoDetailsController animated:YES];

    /*
    gettimeofday(&today, &tz);

    newTodo.content = "test task";
    newTodo.completeDateTime = 0;
    newTodo.dueDateTime = today.tv_sec + 24 * 60 * 60;
    result = MadDbAddTodo(_db, &newTodo);
    MAD_CHK(result == MAD_SUCCESS, result,
            ("MadDbAddTodo() failed result = %d", result));
    
    [_objects insertObject:[NSString stringWithUTF8String:newTodo.content] atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                          withRowAnimation:UITableViewRowAnimationAutomatic];
     */

Exit:
    return;
}
- (void)enterSettings:(id)sender
{}

- (void)toggleEdit: (id)sender
{
    [self.tableView setEditing:YES animated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault
                 reuseIdentifier:CellIdentifier] autorelease];
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }

    NSDate *object = [_objects objectAtIndex:indexPath.row];
    cell.textLabel.text = [object description];
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [_objects removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_todoDetailsController viewWillAppear:YES];
    [self.navigationController pushViewController:_todoDetailsController animated:YES];
}

@end
